package com.lbc.pool;

import java.util.concurrent.*;

//  自定义线程工作：ThreadPoolExecutor
public class Demo2 {
    public static void main(String[] args) {
        //  最大线程到底该如何定义
        //  1、CPU 密集型，几核，就是几，可以保持CPU的效率最高！
        //  2、IO  密集型  一般 >= 判断你程序中有多少个十分耗IO的线程 * 2
        //         程序    15个大型任务，io十分占资源！
        //

        System.out.println(Runtime.getRuntime().availableProcessors());

        ExecutorService threadPool = new ThreadPoolExecutor(
            2,
            5,
            3,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(3),
            Executors.defaultThreadFactory(),
            //new ThreadPoolExecutor.AbortPolicy()  //  银行满了，还有人进来，不处理这个人，抛出异常
            //new ThreadPoolExecutor.CallerRunsPolicy()  //  哪里来的去哪里，不抛出异常
            //new ThreadPoolExecutor.DiscardPolicy()  //  队列满了不会抛出异常，丢掉任务
            new ThreadPoolExecutor.DiscardOldestPolicy()  //  队列满了，尝试和最早的竞争，不抛出异常
        );

        try {
            for (int i = 1; i <= 9; i++) {
                //  最大承载：Deque + max
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+" ok");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //  线程池用完，程序结束，关闭线程池
            threadPool.shutdown();
        }
    }

    //  三大线程池的方法的本质是  ThreadPoolExecutor
    /**
    public ThreadPoolExecutor(int corePoolSize,  //  核心线程池大小
                              int maximumPoolSize,  //  最大线程池大小
                              long keepAliveTime,  //  超时了没有人调用就会释放
                              TimeUnit unit,  //  超时单位
                              BlockingQueue<Runnable> workQueue,  //  阻塞队列
                              ThreadFactory threadFactory,  //  线程工厂，创建线程的，一般不要动它
                              RejectedExecutionHandler handler) {  //  拒绝策略
        if (corePoolSize < 0 ||
                maximumPoolSize <= 0 ||
                maximumPoolSize < corePoolSize ||
                keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }
    **/
}
